package com.example.doubt.dialog.global;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.doubt.R;
import com.mxin.common.log.Log;
import com.mxin.common.log.LogObserver;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Log日志全局浮窗的view管理类
 * 通过订阅 lib_log模块，获取log日志信息
 */
public class LogGlobalViewManager implements LogObserver {

	private static LogGlobalViewManager instance;
	private Context context;
	private View logView;
	private RecyclerView mRecyclerView;
	private LogAdapter mAdapter;
	private List<Log> mLogs = new ArrayList<>();

	private LogGlobalViewManager() {
	}

	public static LogGlobalViewManager getInstance() {
		if (instance == null) {
			instance = new LogGlobalViewManager();
		}
		return instance;
	}

	public View getLogView(Context context) {
		if (logView == null) {
			this.context = context;
			logView = LayoutInflater.from(context).inflate(R.layout.view_global_log, null, false);
			mRecyclerView = logView.findViewById(R.id.recyclerView);
			mAdapter = new LogAdapter(mLogs);
			mRecyclerView.setAdapter(mAdapter);
		}
		return logView;
	}

	public void append(Log log) {
		mLogs.add(log);
		if (mRecyclerView != null) {
			mAdapter.notifyItemChanged(mLogs.size() - 1);
			mRecyclerView.scrollToPosition(mLogs.size() - 1);
		}
	}

	public void clearAll() {
		mLogs.clear();
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void observer(Log log) {
		append(log);
	}


	static class LogAdapter extends RecyclerView.Adapter<LogAdapter.LogViewHolder> {

		private List<Log> logs;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS", Locale.getDefault());

		public LogAdapter(List<Log> logs) {
			this.logs = logs;
		}

		@NonNull
		@Override
		public LogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
			return new LogViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_log, null, false));
		}

		@Override
		public void onBindViewHolder(@NonNull LogViewHolder holder, int position) {
			holder.textView.setText(getLogContent(logs.get(position)));
		}

		@Override
		public int getItemCount() {
			return logs.size();
		}

		private CharSequence getLogContent(Log log) {
			return sdf.format(new Date(log.getTimestamp())) + " " + log.getLogType() + "/" + log.getTag() + ": " + log.getContent();
		}

		static class LogViewHolder extends RecyclerView.ViewHolder {

			private TextView textView;

			public LogViewHolder(@NonNull View itemView) {
				super(itemView);
				textView = itemView.findViewById(R.id.tv_content);
			}
		}
	}


}
